package com.stxx.stiot2.controller;

import com.stxx.framwork.domain.R;
import com.stxx.framwork.domain.model.PageQuery;
import com.stxx.framwork.domain.model.PageResult;
import com.stxx.framwork.tran.TranBean;
import com.stxx.framwork.tran.TranUtils;
import com.stxx.stiot2.domain.Alarm;
import com.stxx.stiot2.event.task.SubscribeAlarmTask;
import com.stxx.stiot2.service.AlarmService;
import org.noear.solon.annotation.*;

import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.function.Function;

@Controller
@Mapping("/alarm")
public class AlarmController {

    @Inject
    AlarmService baseService;
    @Inject
    private  Executor executor;

    @Get
    @Mapping("/list")
    public PageResult<Alarm> list(Alarm bo, PageQuery pageQuery) throws SQLException {
        PageResult<Alarm> r = baseService.pageList(bo,pageQuery);
        return r;
    }


    @Get
    @Mapping("/list-by-device-id")
    public PageResult<Alarm> listByDeviceId(String deviceId, PageQuery pageQuery) throws SQLException {
        PageResult<Alarm> r = baseService.pageListByDeviceId(deviceId,pageQuery);
        return r;
    }


    @Post
    @Mapping("")
    public R<Object> add(@Body Alarm bo) throws SQLException {
        baseService.insert(bo);
        return R.ok("数据保存成功");
    }

    @Put
    @Mapping("/{id}/clear")
    public R<Object> clear(@Path String id, @Param String remark) throws SQLException {
        Alarm alarm =new Alarm();
        alarm.setId(id);
        alarm.setClearTime(LocalDateTime.now());
        alarm.setRemark(remark);
        alarm.setCleared(true);
        baseService.update(alarm);
        executor.execute(new SubscribeAlarmTask(alarm,"clear"));
        return R.ok("数据保存成功");
    }

    @Put
    @Mapping("/{id}/confirm")
    public R<Object> confirm(@Path String id, @Param String remark) throws SQLException {
        Alarm alarm =new Alarm();
        alarm.setId(id);
        alarm.setConfirmTime(LocalDateTime.now());
        alarm.setRemark(remark);
        alarm.setConfirmed(true);
        baseService.update(alarm);
        executor.execute(new SubscribeAlarmTask(alarm,"confirm"));
        return R.ok("数据保存成功");
    }

    @Delete
    @Mapping("/{ids}")
    public R<Object> remove(@Path String[] ids) throws SQLException {
        baseService.deleteByIds(ids);
        return R.ok("数据删除成功");
    }
}
